#include "../logs/ltylog.h"
#include <unistd.h>

using namespace std;

enum class TimeGap {
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};

class RollByTimeSink : public ltylog::LogSink {
public:
    //构造时传入文件名并打开，将操作句柄ofs管理起来
    RollByTimeSink(const std::string &basename, TimeGap gap_type) : _basename(basename) {
        switch (gap_type) {
            case TimeGap::GAP_SECOND:
                _gap_size = 1;
                break;
            case TimeGap::GAP_MINUTE:
                _gap_size = 60;
                break;
            case TimeGap::GAP_HOUR:
                _gap_size = 3600;
                break;
            case TimeGap::GAP_DAY:
                _gap_size = 3600 * 24;
                break;
        }
        _cur_gap = _gap_size == 1 ? ltylog::util::Date::now() : ltylog::util::Date::now() % _gap_size;//获取当前是第几个时间段
        std::string filename = createNewFile();
        ltylog::util::File::createDirectory(ltylog::util::File::path(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }

    void log(const char *data, size_t len) {
        time_t cur = ltylog::util::Date::now();
        if ((cur % _gap_size) != _cur_gap) {
            _ofs.close();
            std::string filename = createNewFile();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        _ofs.write(data, len);
        assert(_ofs.good());
    }
private:
    std::string createNewFile() {
        time_t t = ltylog::util::Date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900;
        filename << lt.tm_mon + 1;
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << ".log";
        return filename.str();//filename是stringstream，要转换成string

    }
private:
    std::string _basename;
    std::ofstream _ofs;//操作句柄
    size_t _cur_gap;//当前时间段
    size_t _gap_size;//时间段大小
};
void test_log(const string& name) {
    // //正常测试
    ltylog::Logger::ptr logger = ltylog::LoggerManager::getInstance().getLogger(name);

    logger->debug("%s", "测试日志");
    logger->info("%s", "测试日志");
    logger->warn("%s", "测试日志");
    logger->error("%s", "测试日志");
    logger->fatal("%s", "测试日志");
    // //宏测试，默认日志器输出到stdout
    // DEBUG("%s","测试日志");
    // INFO("%s","测试日志");
    // WARN("%s","测试日志");
    // ERROR("%s","测试日志");
    // FATAL("%s","测试日志");
    size_t count = 0;
    while (count < 50000) {
        // FATAL("%s","测试日志");
        logger->fatal("%s", "测试日志");
        count++;
    }
}
int main() {
//     cout<< ltylog::util::Date::now()<<endl;
//     const string pathname="./logfile";
//     ltylog::util::File::createDirectory(ltylog::util::File::path(pathname));

//  //    format测试
//     ltylog::LogMsg msg(ltylog::LogLevel::value::INFO,53,"main.c","root","功能测试...");
//     ltylog::Formatter fmt;
//     std::string str =fmt.format(msg);
//     cout <<str <<endl;
//     ltylog::LogSink::ptr stdout_lsp=ltylog::SinkFactory::create<ltylog::StdoutSink>();
//     ltylog::LogSink::ptr file_lsp=ltylog::SinkFactory::create<ltylog::FileSink>("./logfile/test.log");
//     ltylog::LogSink::ptr roll_lsp=ltylog::SinkFactory::create<ltylog::RollBySizeSink>("./logfile/roll-",1024*1024);
//     ltylog::LogSink::ptr time_lsp=ltylog::SinkFactory::create<RollByTimeSink>("./logfile/roll-",TimeGap::GAP_SECOND);
//     stdout_lsp->log(str.c_str(),str.size());
//     file_lsp->log(str.c_str(),str.size());
//     size_t cursize=0;
//     size_t count=0;
//     while(cursize<1024*1024*10)
//     {
//         std::string tmp=str + to_string(count++);
//         roll_lsp->log(tmp.c_str(),tmp.size());
//         cursize+=tmp.size();
//     }

    //time_lsp测试
    // time_t old=ltylog::util::Date::now();
    // while(ltylog::util::Date::now()<old+5)
    // {
    //     time_lsp->log(str.c_str(),str.size());
    //     usleep(1000);
    // }

    // // logger测试
//     std::string logger_name="sync_logger";
//     ltylog::LogLevel::value limit=ltylog::LogLevel::value::WARN;
//     ltylog::Formatter::ptr fmt(new ltylog::Formatter("[%d{%H:%M:%S}][%c][%f:%l][%p]%T%m%n"));
//     ltylog::LogSink::ptr stdout_lsp=ltylog::SinkFactory::create<ltylog::StdoutSink>();
//     ltylog::LogSink::ptr file_lsp=ltylog::SinkFactory::create<ltylog::FileSink>("./logfile/test.log");
//     ltylog::LogSink::ptr roll_lsp=ltylog::SinkFactory::create<ltylog::RollBySizeSink>("./logfile/roll-",1024*1024);
//     std::vector<ltylog::LogSink::ptr> sinks={stdout_lsp,file_lsp,roll_lsp};
//     ltylog::Logger::ptr logger(new ltylog::SyncLogger(logger_name,limit,fmt,sinks));
//
//     logger->debug(__FILE__,__LINE__,"%s","测试日志");
//     logger->info(__FILE__,__LINE__,"%s","测试日志");
//     logger->warn(__FILE__,__LINE__,"%s","测试日志");
//     logger->error(__FILE__,__LINE__,"%s","测试日志");
//     logger->fatal(__FILE__,__LINE__,"%s","测试日志");
//     size_t cursize=0,count=0;
//     std::string str="测试日志-";
//     while(cursize<1024*1024*10)
//     {
//         logger->fatal(__FILE__,__LINE__,"测试日志-%d",count++);
//         std::string tmp=str + to_string(count++);
//         cursize+=20;
//     }

//    //buffer缓冲区测试
//    std::ifstream ifs("./logfile/test.log",std::ios::binary);
//    if(ifs.is_open()==false) return -1;
//    ifs.seekg(0,std::ios::end);//跳转到文件末尾
//    size_t fsize=ifs.tellg();//获取当前读写位置相当于起始位置的偏移量
//    ifs.seekg(0,std::ios::beg);//跳转到文件起始位置
//    std::string body;
//    body.resize(fsize);
//    ifs.read(&body[0],fsize);
//    if(ifs.good()==false) {std::cout<<"read error\n";return -1;}
//    ifs.close();
//
//    ltylog::Buffer buffer;
//    for(int i=0;i<body.size();i++)
//    {
//        buffer.push(&body[i],1);
//    }
//    std::ofstream ofs("./logfile/tmp.log",std::ios::binary);
//    size_t rsize=buffer.readAbleSize();
//    for(int i=0;i<rsize;i++)
//    {
//        ofs.write(buffer.begin(),1);
//        buffer.moveReader(1);
//    }
//    ofs.close();


//    // looper异步测试
    std::unique_ptr<ltylog::LoggerBuilder> builder(new ltylog::GloablLoggerBuilder());
    builder->buildLoggerName("async_logger");
    builder->buildLoggerLevel(ltylog::LogLevel::value::DEBUG);
    // builder->buildFormatter("[%c]%m%n");//指定格式，不写就是默认格式
    builder->buildLoggerType(ltylog::LoggerType::LOGGER_ASYNC);
//     builder->buildEnableUnSafeAsync(); //指定不安全异步测试，默认安全
    builder->buildSink<ltylog::FileSink>("./logfile/sync.log");
    // builder->buildSink<ltylog::StdoutSink>();//多方向落地测试，可以同时落地到stdout和File
    builder->build();
    test_log("async_logger");
    return 0;
}
